package com.ksyun.alert.calculate;

import com.ksyun.alert.biz.bo.timing.TimingSectionCalculateParamsBO;
import com.ksyun.alert.biz.bo.timing.TimingExpressionResolveBO;
import com.ksyun.alert.entity.AlertMetricsDO;
import com.ksyun.alert.entity.AlertRecordsDO;
import com.ksyun.alert.entity.AlertRulesDO;
import com.ksyun.alert.entity.MonitorDatasDO;
import com.ksyun.alert.service.*;
import com.ksyun.alert.service.impl.CalculateTimingServiceImpl;
import com.ksyun.alert.utils.AggregateOperations.Params.RateParam;
import com.ksyun.alert.utils.QLExpressUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.ksyun.alert.utils.QLExpressUtil.doCalculate;

/**
 * 定时计算类
 * @author hantou
 * @date 2024-04-30
 * 定时任务调度的用于计算的方法类
 */
@Component
@Slf4j
public class CalculateTiming {

    @Resource
    private AlertRulesService alertRulesService;

    @Resource
    private CalculateTimingService calculateTimingService;

    public void calculateTiming(long startTimestamp) {
        List<AlertRulesDO> timingRules = alertRulesService.getTimingRules();
        doCalculateTiming(startTimestamp, timingRules);
    }

    public void test(Long startTimestamp) throws Exception {
        List<AlertRulesDO> timingRules = alertRulesService.getTimingRules();
        doCalculateTiming(startTimestamp, timingRules);
    }

    /**
     * 解析定时计算规则和参数列表
     * @param nowTimestamp 当前时间戳
     * @param timingRuleList 定时计算告警规则列表
     */
    private void doCalculateTiming(long nowTimestamp, List<AlertRulesDO> timingRuleList) {
        for (AlertRulesDO alertRulesDO : timingRuleList) {
            // 判断规则中是否存在[time]
            String expression = alertRulesDO.getExpression();
            String regex = "\\[(.*?)\\]";
            Pattern pattern = Pattern.compile(regex);
            boolean hasTimePeriod = pattern.matcher(expression).find();
            // 不包含时间段就是定时计算的瞬时数据计算
            if(!hasTimePeriod){
                calculateTimingService.doTransientCalculate(nowTimestamp, alertRulesDO);
            }else {// 包含时间段就是定时区间数据计算
                calculateTimingService.doSectionCalculate(nowTimestamp, alertRulesDO);
            }
        }
    }

}
